package personal.lijun.skeleton.springcloud.gateway;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufMono;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/25 17:57
 */
@Controller
@RequestMapping("/")
public class CaptchaImageCreateController {

    private Producer captchaProducer = null;

    @Autowired
    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @RequestMapping("/captcha-image")
    public Mono<Void> handleRequest(WebSession session, ServerHttpResponse response) throws Exception {
        DataBufferFactory bufferFactory = response.bufferFactory();
        response.getHeaders().set("Expires", "0");
        // Set standard HTTP/1.1 no-cache headers.
        response.getHeaders().set("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.getHeaders().set("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.getHeaders().set("Pragma", "no-cache");
        // return a jpeg
        response.getHeaders().set("Content-Type","image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        session.getAttributes().put(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        byte[] uppedContent;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", byteArrayOutputStream);
        uppedContent = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        DataBuffer dataBuffer = bufferFactory.wrap(uppedContent);
        return response.writeAndFlushWith(ByteBufMono.just(Mono.just(dataBuffer)));
    }
}
